package com.cqut.servlet;

import com.alibaba.fastjson.JSON;
import com.cqut.utils.ResultData;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

public class login2Servlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        String action = req.getParameter("action") == null ? "" : req.getParameter("action");
        switch (action) {
            case "login":
                login(req, resp);
                break;
            case "logout":
                logout(req, resp);
                break;
            case "register":
                register(req, resp);
                break;
            default:
                break;

        }

//        PrintWriter out = resp.getWriter();
//        String username = req.getParameter("username");
//        String password = req.getParameter("password");
////
//        String validCode = req.getParameter("validCode");
//        HttpSession session = req.getSession();
//        ResultData rd = new ResultData();
//        if (!session.getAttribute("validCode").equals(validCode)) {
//            rd.setCode("401");
//            rd.setMsg("验证码有误！");
////            out.write(JSON.toJSONString(rd1));
//            return;
//        }
//
//        String driver= "com.mysql.cj.jdbc.Driver";
//        String URL= "jdbc:mysql://localhost:3306/staff?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8&useSSL=false";
//        String dbuser= "root";
//        String dbpwd= "181919";
//        try{
//            Class.forName(driver);
//            Connection conn = DriverManager.getConnection(URL,dbuser,dbpwd);
//            String sql = "select * from staff where tuser= ? and pwd= ?";
//            PreparedStatement pstmt = conn.prepareStatement(sql);
//            pstmt.setString(1,username);
//            pstmt.setString(2,password);
//            ResultSet rs = pstmt.executeQuery();
////            ResultData rd = new ResultData();
//            if(rs.next()){
////                resp.sendRedirect("index.jsp");
////                HttpSession session = req.getSession();
//                session.setAttribute("username", username);
//                rd.setCode("201");
//                rd.setMsg("登录成功");
//            }
//            else{
////                resp.sendRedirect("login2.jsp");
//                rd.setCode("4041");
//                rd.setMsg("用户名或密码有误");
//            }
//
//        }
//        catch (Exception e)
//        {
//            System.out.println(e.getMessage());
//        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out = resp.getWriter();
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String select = req.getParameter("select");
        String validCode = req.getParameter("validCode").toLowerCase();
        HttpSession session = req.getSession();
        String sessionValidCode = session.getAttribute("validCode").toString().toLowerCase();
        ResultData rd = new ResultData();

//        if (!sessionValidCode.equals(validCode)) {//验证码不同
//            rd.setCode("401");
//            rd.setMsg("验证码有误！");
//            out.write(JSON.toJSONString(rd));
//            return;
//        }

        String sql ="";
        //根据select的不同选择不同角色的数据库进行验证登录
        switch (select){
            case "user":
                sql = "select * from user where username= ? and password= ?";
                break;
            case "student":
                sql = "select * from student where sno= ? and password= ?";
                break;
            case "teacher"://待定
                sql = "select * from teacher where teacherno= ? and password= ?";
                break;
            default:System.out.println("error");
        }


        //数据库基本信息
        String driver= "com.mysql.cj.jdbc.Driver";
        String url= "jdbc:mysql://localhost:3306/work?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8&useSSL=false";
        String dbuser= "root";
        String dbpwd= "123456";
        try{
            Class.forName(driver);
            Connection conn = DriverManager.getConnection(url,dbuser,dbpwd);
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,username);
            pstmt.setString(2,password);
            ResultSet rs = pstmt.executeQuery();

//            ResultData rd = new ResultData();
            if(rs.next()){
//                resp.sendRedirect("index.jsp");
//                HttpSession session = req.getSession();
                session.setAttribute("username", username);
                rd.setCode("201");
                rd.setMsg("登录成功");
                out.write(JSON.toJSONString(rd));
            }
            else{
//                resp.sendRedirect("login2.jsp");
                rd.setCode("4041");
                rd.setMsg("用户名或密码有误");
                out.write(JSON.toJSONString(rd));
            }

        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }

    }

    private void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        if(session!=null){
            session.removeAttribute("username");
            session.invalidate();
        }
        resp.sendRedirect("/lab00/login2.jsp");
    }

    private void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        String driver= "com.mysql.cj.jdbc.Driver";
        String url= "jdbc:mysql://localhost:3306/staff?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8&useSSL=false";
        String dbuser= "root";
        String dbpwd= "181919";
        try{
            PrintWriter out = resp.getWriter();
            Class.forName(driver);
            Connection conn = DriverManager.getConnection(url,dbuser,dbpwd);
            String sql = "insert into staff(tuser,pwd) values (?,?)";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,username);
            pstmt.setString(2,password);

            ResultData rd = new ResultData();
            if(pstmt.executeUpdate() > 0 ){
                rd.setCode("200");
                rd.setMsg("注册成功");
            }
            else{
                rd.setCode("501");
                rd.setMsg("注册失败");
            }
            out.write(JSON.toJSONString(rd));
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}
